from django.shortcuts import render, HttpResponse, redirect, reverse
from django.db.models import Q
from django.core.paginator import Paginator
from django.conf import settings
from django.views.decorators.http import require_POST
from django.http import JsonResponse
import json
from django.contrib.auth.decorators import login_required

from xadmin.models import NodeGroup, Node
from xadmin.forms import nodegroup, node
from xadmin.nodeBll import node_tree, node_tree_list, node_order_tree
from xadmin.plugins.auditlog import add_log


@login_required
def node_list(request):
    print(request)
    mbx = ('栏目管理', '栏目')
    siteid = request.GET.get('siteid', '1')
    node_queryset = Node.objects.filter(site_id=siteid, parent_node=None)

    #node_trees = node_tree.create_tree(node_list)
    node_list = []
    node_trees = node_order_tree(node_list, node_queryset)
    context = {
        'node_list': node_trees,
        'siteid': siteid,
        'mbx': mbx
    }
    return render(request, 'xadmin/node/list.html', context)


#栏目字段分组配置
basic_colums = ('parent_node', 'name', 'sub_name', 'slogen1', 'slogen2', 'index_name', 'force_url', 'open_type',
                'node_type', 'brief', 'picture', 'icon',
                'cover_picture', 'background_picture', 'is_active', 'is_search')
config_colums = ('is_active', 'is_search')
template_colums = ('template_type', 'gather_template', 'list_template', 'content_template', 'router')
seo_colums = ('seo_title', 'seo_keywords', 'seo_description')


@login_required
def node_add(request):
    siteid = request.GET.get('siteid')
    mbx = ('栏目管理', '栏目', '添加栏目')
    if request.method == 'GET':
        node_form = node.NodeForm()

        context = {
            'siteid': siteid,
            'basic_colums': basic_colums,
            'config_colums': config_colums,
            'template_colums': template_colums,
            'seo_colums': seo_colums,
            'node_form': node_form,
            'mbx': mbx
        }

        return render(request, 'xadmin/node/add.html', context)
    else:
        node_form = node.NodeForm(request.POST, request.FILES)
        if node_form.is_valid():
            new_node = node_form.save(commit=False)
            new_node.site_id = siteid
            if new_node.parent_node is None:
                new_node.node_path = '0'
                new_node.node_level = 1
                max_node = Node.objects.filter(site_id=siteid, node_level=1).order_by('-order_num').first()
                if max_node:
                    new_node.order_num = max_node.order_num + 1
                else:
                    new_node.order_num = 1
                new_node.save()
                action = '添加了栏目《%s》' % new_node.name
                add_log(request, action, siteid)
                return redirect('%s?siteid=%s' % (reverse('nodelist'), siteid))
            else:
                if new_node.parent_node.node_path != '0':
                    new_node.node_path = new_node.parent_node.node_path + ',' + str(new_node.parent_node.id)
                else:
                    new_node.node_path = new_node.parent_node.id
                new_node.node_level = new_node.parent_node.node_level + 1
                max_node = Node.objects.filter(parent_node=new_node.parent_node).order_by('-order_num').first()
                if max_node:
                    new_node.order_num = max_node.order_num + 1
                else:
                    new_node.order_num = 1
                new_node.save()
                # 修改父栏目的栏目类型
                parent_node = Node.objects.get(id=new_node.parent_node.id)
                parent_node.node_type = ''
                parent_node.save()
                action = '添加了栏目《%s》' % new_node.name
                add_log(request, action, siteid)
                return redirect('%s?siteid=%s' % (reverse('nodelist'), siteid))
        else:
            error = node_form.errors
            #print(error)
            context = {
                'siteid': siteid,
                'basic_colums': basic_colums,
                'config_colums': config_colums,
                'template_colums': template_colums,
                'seo_colums': seo_colums,
                'node_form': node_form,
                'error': error,
                'mbx': mbx
            }
            return render(request, 'xadmin/node/add.html', context)


@login_required
def node_edit(request, nodeid):
    siteid = request.GET.get('siteid')
    mbx = ('栏目管理', '栏目', '编辑栏目')
    node_obj = Node.objects.get(id=nodeid)
    old_parent_id = node_obj.parent_node_id

    if request.method == 'GET':
        node_form = node.NodeForm(instance=node_obj)
        context = {
            'siteid': siteid,
            'basic_colums': basic_colums,
            'config_colums': config_colums,
            'template_colums': template_colums,
            'seo_colums': seo_colums,
            'node_form': node_form,
            'mbx': mbx
        }
        return render(request, 'xadmin/node/add.html', context)
    else:
        #parent_node_id = request.POST.get('parent_node')

        node_form = node.NodeForm(request.POST, request.FILES, instance=node_obj)
        if node_form.is_valid():
            m_node = node_form.save(commit=False)
            #修改了父栏目
            if m_node.parent_node and m_node.parent_node_id != old_parent_id:
                if m_node.node_path != '0':
                    m_node.node_path = m_node.parent_node.node_path + ',' + str(m_node.parent_node_id)
                else:
                    m_node.node_path = str(m_node.parent_node_id)
                m_node.node_level = m_node.parent_node.node_level + 1
            m_node.save()

            action = '修改了栏目《%s》' % node_form.cleaned_data['name']
            add_log(request, action, siteid)
            return redirect('%s?siteid=%s' % (reverse('nodelist'), siteid))
        else:
            error = node_form.errors
            context = {
                'siteid': siteid,
                'basic_colums': basic_colums,
                'config_colums': config_colums,
                'template_colums': template_colums,
                'seo_colums': seo_colums,
                'node_form': node_form,
                'error': error,
                'mbx': mbx
            }
            return render(request, 'xadmin/node/add.html', context)


@login_required
@require_POST
def node_del(request):
    try:
        nodeid = request.POST.get('nodeid')
        node_obj = Node.objects.get(id=nodeid)
        node_obj.delete()
        action = '删除了栏目《%s》' % node_obj.name
        add_log(request, action, node_obj.site_id)
        return JsonResponse({'code': '200', 'message': '删除成功'})
    except Exception as e:
        print(e)
        return JsonResponse({'code': '404', 'message': '栏目或子栏目下可能存在文章, 不能被删除'})


@login_required
def nodegroup_list(request):
    siteid = request.GET.get('siteid')
    nodegroups_list = NodeGroup.objects.filter(site_id=siteid)
    mbx = ('栏目管理', '栏目组管理')

    context = {
        'nodegroup_list': nodegroups_list,
        'siteid': siteid,
        'mbx': mbx
    }
    return render(request, 'xadmin/node/nodegroup.html', context)


@login_required
def nodegroup_add(request):
    siteid = request.GET.get('siteid')
    mbx = ('栏目管理', '栏目', '新建栏目组')
    node_list_value = Node.objects.filter(site_id=siteid, is_active=True).values()
    node_tree_json = node_tree_list(node_list_value)

    if request.method == 'GET':
        nodegroup_form = nodegroup.NodeGroupForm()
        context = {
            'nodegroup_form': nodegroup_form,
            'siteid': siteid,
            'node_tree_json': node_tree_json,
            'mbx': mbx
        }
        return render(request, 'xadmin/node/nodegroupadd.html', context)
    else:
        group_form = nodegroup.NodeGroupForm(request.POST, request.FILES)
        ids = request.POST.get('ids')

        if group_form.is_valid():
            new_group = group_form.save(commit=False)
            new_group.site_id = siteid
            new_group.save()

            #找到选中的栏目
            nodes = Node.objects.filter(id__in=ids.split(','))
            #添加多对多数据
            new_group.node.add(*nodes)
            action = '添加了栏目组《%s》' % new_group.name
            add_log(request, action, new_group.site_id)
            return redirect('%s?siteid=%s' % (reverse('nodegrouplist'), siteid))
        else:
            context = {
                'siteid': siteid,
                'nodegroup_form': group_form,
                'mbx': mbx
            }
            return render(request, 'xadmin/node/nodegroupadd.html', context)


@login_required
def nodegroup_edit(request, nodegroupid):
    siteid = request.GET.get('siteid')
    mbx = ('栏目管理', '栏目', '编辑栏目组')
    nodegroup_obj = NodeGroup.objects.get(id=nodegroupid)
    nodes_objs = nodegroup_obj.node.all()
    node_list_value = Node.objects.filter(site_id=siteid, is_active=True).values()
    node_tree_json = node_tree_list(node_list_value)

    if request.method == 'GET':
        nodegroup_form = nodegroup.NodeGroupForm(instance=nodegroup_obj)
        context = {
            'siteid': siteid,
            'nodegroup_form': nodegroup_form,
            'select_ids': json.dumps([x.id for x in nodes_objs]),
            'node_tree_json': node_tree_json,
            'mbx': mbx
        }
        return render(request, 'xadmin/node/nodegroupadd.html', context)
    else:
        group_form = nodegroup.NodeGroupForm(request.POST, request.FILES, instance=nodegroup_obj)
        ids = request.POST.get('ids', '')
        print('ids:', ids)
        # 找到选中的栏目
        if ids:
            nodes = Node.objects.filter(id__in=ids.split(','))
        if group_form.is_valid():
            group_obj = group_form.save()
            if ids:
                group_obj.node.clear()
                group_obj.node.add(*nodes)
            action = '添加了栏目组《%s》' % group_obj.name
            add_log(request, action, group_obj.site_id)
            return redirect('%s?siteid=%s' % (reverse('nodegrouplist'), siteid))
        else:
            context = {
                'siteid': siteid,
                'nodegroup_form': group_form,
                'mbx': mbx
            }
            return render(request, 'xadmin/node/nodegroupadd.html', context)

@login_required
@require_POST
def nodegroup_del(request):
    nodegroupid = request.POST.get('nodegroupid')
    nodegroup_obj = NodeGroup.objects.get(id=nodegroupid)
    mess = {}
    try:
        nodegroup_obj.delete()
        mess['status'] = '200'
        mess['message'] = '删除成功'
        action = '删除了栏目组《%s》' % nodegroup_obj.name
        add_log(request, action, nodegroup_obj.site_id)
    except Exception as e:
        mess['status'] = '500'
        mess['message'] = '删除失败'
    return JsonResponse(mess)

@login_required
def test(request):
    siteid = request.GET.get('siteid')
    node_list_value = Node.objects.filter(site_id=siteid, is_active=True).values()
    node_tree_json = node_tree_list(node_list_value)
    nodegroup_form = nodegroup.NodeGroupForm()
    context = {
        'node_tree_json': node_tree_json,
    }
    return render(request, 'xadmin/node/test.html', context)


@login_required
@require_POST
def nodegroups_del(request):
    siteid = request.GET.get('siteid')
    mess = {}
    try:
        groupids = request.POST.get('groupids')
        groups = NodeGroup.objects.filter(id__in=groupids.split(','))
        groups.delete()
        mess['status'] = '200'
        mess['msg'] = '删除成功'
        action = '删除了栏目组 %s' % ','.join(['《x》' % x.name for x in groups])
        add_log(request, action, siteid)
    except:
        mess['status'] = '500'
        mess['msg'] = '删除失败'
    return JsonResponse(mess)


@login_required
@require_POST
def node_move(request):
    mess = {}
    id = request.POST.get('id')
    action = request.POST.get('act')
    if action == 'moveup':
        cur_obj = Node.objects.get(id=id)
        switch_obj = Node.objects.filter(parent_node_id=cur_obj.parent_node_id, order_num__lt=cur_obj.order_num).last()
        if switch_obj:
            cur_obj.order_num, switch_obj.order_num = switch_obj.order_num, cur_obj.order_num
            cur_obj.save()
            switch_obj.save()
            mess['status'] = '200'
            mess['msg'] = '操作成功'
            action = '修改了栏目组排序 %s' % cur_obj.name
            add_log(request, action, cur_obj.site_id)
        else:
            mess['status'] = '404'
            mess['msg'] = '已经移到顶部了...'
    else:
        cur_obj = Node.objects.get(id=id)
        switch_obj = Node.objects.filter(parent_node_id=cur_obj.parent_node_id, order_num__gt=cur_obj.order_num).first()
        if switch_obj:
            cur_obj.order_num, switch_obj.order_num = switch_obj.order_num, cur_obj.order_num
            cur_obj.save()
            switch_obj.save()
            mess['status'] = '200'
            mess['msg'] = '操作成功'
            action = '修改了栏目组排序 %s' % cur_obj.name
            add_log(request, action, cur_obj.site_id)
        else:
            mess['status'] = '404'
            mess['msg'] = '已经移到底部了...'
    return JsonResponse(mess)
